package com.atguigu.tingshu.cdc.album;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import top.javatool.canal.client.annotation.CanalTable;
import top.javatool.canal.client.handler.EntryHandler;

import java.util.Set;


/**
 * Change Data Capture数据变更捕获
 *
 */
@Slf4j
@Component
@CanalTable("track_info") //监听变更表
public class TrackCdcHandler implements EntryHandler<TrackCDC> {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 新增操作：
     *
     * @param trackCDC 新增记录封装Java对象
     */
    @Override
    public void insert(TrackCDC trackCDC) {
        log.info("监听到Canal服务端新增操作：{}", trackCDC);

    }

    /**
     * 更新操作
     *
     * @param before 更新前记录封装Java对象
     * @param after  更新后记录封装Java对象
     */
    @Override
    public void update(TrackCDC before, TrackCDC after) {
        log.info("监听到Canal服务端修改操作：{}", after);
        String pattern = "userTrack:" + after.getUserId() + ":*:*";
        Set<String> keys = redisTemplate.keys(pattern);
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除操作
     *
     * @param trackCDC 删除前记录
     */
    @Override
    public void delete(TrackCDC trackCDC) {
        log.info("监听到Canal服务端删除操作：{}", trackCDC);
        String pattern = "userTrack:" + trackCDC.getUserId() + ":*:*";
        Set<String> keys = redisTemplate.keys(pattern);
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
}
